package com.fablesoft.projectdatacollect.ui;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

import com.authentication.asynctask.AsyncFingerprint;
import com.authentication.utils.ToastUtil;
import com.fablesoft.projectdatacollect.MyApplication;
import com.fablesoft.projectdatacollect.R;
import com.fablesoft.projectdatacollect.bean.BaseResponse;
import com.fablesoft.projectdatacollect.bean.Campaign;
import com.fablesoft.projectdatacollect.bean.CampaignListResponse;
import com.fablesoft.projectdatacollect.bean.MemberBean;
import com.fablesoft.projectdatacollect.bean.MemberListResponse;
import com.fablesoft.projectdatacollect.bean.MemberResponse;
import com.fablesoft.projectdatacollect.http.HttpListener;
import com.fablesoft.projectdatacollect.http.HttpThread;
import com.fablesoft.projectdatacollect.http.HttpUploadThread;
import com.fablesoft.projectdatacollect.ui.fragment.DialogFragmentTip;
import com.fablesoft.projectdatacollect.util.CommonUtils;
import com.fablesoft.projectdatacollect.util.Config;
import com.fablesoft.projectdatacollect.view.MyRefreshListView;
import com.fablesoft.projectdatacollect.view.MyRefreshListView.RefreshListViewListener;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import android_serialport_api.FingerprintAPI;
import android_serialport_api.SerialPortManager;

public class SignInActivity extends BaseRequestActivity implements
		RefreshListViewListener {

	private CopyOnWriteArrayList<MemberBean> memberList = new CopyOnWriteArrayList<MemberBean>();;
	private MyRefreshListView memberListView;
	private View noDataLayout;
	private View noDataTip;
	private View connectionFailedTip;
	private int pagesize = 10;
	private int page = 1;
	private static final int REFRESH_INFO_REQUEST_CODE = 101;
	private static final int INFO_REQUEST_CODE = 102;
	private static final int LOAD_INFO_REQUEST_CODE = 103;
	private static final int FINGERPRINT_CODE = 104;
	private static final int SIGN_IN_CODE = 106;
	private static final int DELETE_SIGN_IN_CODE = 107;
	private View loadingLayout;
	private View loadingProgressbar;
	private AsyncFingerprint asyncFingerprint;
	private ImageView fingerprintView;
	private String id;
	private TextView signNum;
	private String deleteSignId;
    private SignBroadcastReceiver receiver;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_sign_in);
		boolean isExit = false;
        register();
		if (!SerialPortManager.getInstance().isOpen()
				&& !SerialPortManager.getInstance().openSerialPort()) {
			ToastUtil.showToast(this, R.string.open_serial_fail);
			isExit = true;
		}
		if (isExit) {
			// return;
		}
		id = getIntent().getStringExtra("id");
		initView();
		initData();
	}

	private void initView() {
		memberListView = (MyRefreshListView) findViewById(R.id.member_list);
		noDataLayout = findViewById(R.id.no_data_reload_layout);
		noDataTip = findViewById(R.id.no_data_tip);
		connectionFailedTip = findViewById(R.id.connection_failed_tip);
		fingerprintView = (ImageView) findViewById(R.id.fingerprint_view);
		loadingLayout = findViewById(R.id.loading_layout);
		loadingProgressbar = findViewById(R.id.loading_progressbar);
		signNum = (TextView) findViewById(R.id.sign_in_num);
		View back = findViewById(R.id.back);
		View reloadBtn = findViewById(R.id.reload_btn);
		back.setOnClickListener(mOnClickListener);
		reloadBtn.setOnClickListener(mOnClickListener);
		memberListView.setAdapter(mAdapter);
		memberListView.setRefreshListViewListener(this);
		memberListView.setPullLoadEnable(false);
		memberListView.setPullRefreshEnable(false);

		if (asyncFingerprint == null) {
			asyncFingerprint = new AsyncFingerprint(MyApplication.getInstance()
					.getHandlerThread().getLooper(), mHandler);
			asyncFingerprint
					.setFingerprintType(FingerprintAPI.SMALL_FINGERPRINT_SIZE);
		}
	}

	private void register(){
        IntentFilter filter = new IntentFilter(CommonUtils.SIGN_BROADCAST_RECEIVER);
        receiver = new SignBroadcastReceiver();
        registerReceiver(receiver, filter);
    }

    private void unRegister(){
        unregisterReceiver(receiver);
    }

	private OnClickListener mOnClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.reload_btn:
				initData();
				break;
			case R.id.back:
				Intent i = new Intent();
				i.putExtra("count", signNum.getText());
				setResult(202, i);
				finish();
				break;
			case R.id.delete_btn:
				deleteSignId = v.getTag() == null ? null : v.getTag().toString();
				createPromptDialog(SignInActivity.this, null, "确定删除？", null, null, new ConfirmClickListener(){
					@Override
					public void confirmClickImp() {
						new HttpThread(Config.DELETE_SIGN_IN_URL + deleteSignId, new HttpListener() {
							@Override
							public void onRequestFinish(BaseResponse response) {
								Message msg = mHandler.obtainMessage();
								msg.obj = response;
								msg.what = DELETE_SIGN_IN_CODE;
								mHandler.sendMessage(msg);
							}
							
							@Override
							public void onNotLogin(BaseResponse response) {
								loginExpire();
								SignInActivity.this.onNotLogin(response);
							}
						}, null, BaseResponse.class).start();
						
					}
					
				});
				break;
			}
		}
	};

	@Override
	public void onBackPressed() {
		Intent i = new Intent();
		i.putExtra("count", signNum.getText());
		setResult(202, i);
		finish();
	};

	private void showLoading() {
		if (loadingProgressbar != null) {
			Animation loadAnimation = AnimationUtils.loadAnimation(
					SignInActivity.this, R.anim.loading);
			loadingProgressbar.startAnimation(loadAnimation);
		}
		if (loadingLayout != null) {
			loadingLayout.setVisibility(View.VISIBLE);
		}
	}

	private void dismissLoading() {
		if (loadingProgressbar != null) {
			loadingProgressbar.clearAnimation();
		}
		if (loadingLayout != null) {
			loadingLayout.setVisibility(View.GONE);
		}
	}

	public void initData() {
		Map<String, Object> params = new HashMap<String, Object>();
		Campaign campaign = new Campaign();
		campaign.setActivityId(id);
		params.put("mapParams", campaign);
		// params.put("size", pagesize);
		// params.put("page", page);
		showLoading();
		sendRequest(Config.SIGN_LIST_URL, params, MemberListResponse.class);
	}

	class ViewHolder {
		TextView name;
		TextView post;
		TextView department;
		TextView time;
		TextView delete;
		View line;
	}

	private BaseAdapter mAdapter = new BaseAdapter() {

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder viewHolder = null;
			if (convertView == null) {
				viewHolder = new ViewHolder();
				convertView = LayoutInflater.from(SignInActivity.this).inflate(
						R.layout.member_list_item, null);
				viewHolder.name = (TextView) convertView
						.findViewById(R.id.name);
				viewHolder.post = (TextView) convertView
						.findViewById(R.id.post);
				viewHolder.department = (TextView) convertView
						.findViewById(R.id.department);
				viewHolder.time = (TextView) convertView
						.findViewById(R.id.time);
				viewHolder.delete = (TextView) convertView
						.findViewById(R.id.delete_btn);
				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}
			if (memberList.get(position).getId()
					.equals(viewHolder.delete.getTag())) {
				return convertView;
			}
			viewHolder.name.setText(memberList.get(position).getPersonName());
			viewHolder.delete.setTag(memberList.get(position).getId());
			viewHolder.post.setText(memberList.get(position).getPostName());
			viewHolder.department.setText(memberList.get(position)
					.getDepartmentName());
			viewHolder.time.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm")
					.format(memberList.get(position).getCreatedTime()));
			viewHolder.delete.setOnClickListener(mOnClickListener);
			return convertView;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public int getCount() {
			return memberList.size();
		}
	};

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case REFRESH_INFO_REQUEST_CODE:
				updateRefreshData(msg.obj);
				break;
			case LOAD_INFO_REQUEST_CODE:
				updateLoadData(msg.obj);
				break;
			case INFO_REQUEST_CODE:
				updateData(msg.obj);
				break;
			case AsyncFingerprint.SHOW_FINGER_IMAGE:
				byte[] data = (byte[]) msg.obj;
				Bitmap image = BitmapFactory.decodeByteArray(data, 0,
						data.length);
				fingerprintView.setImageBitmap(image);
				if (asyncFingerprint != null) {
					asyncFingerprint.setStop(true);
				}
				mHandler.removeMessages(FINGERPRINT_CODE);
				createLoadingDialog(SignInActivity.this);
				showDialog("签到中...");
				signIn(data);
				break;
			case SIGN_IN_CODE:
				dismissDialog();
				mHandler.sendEmptyMessage(FINGERPRINT_CODE);
				MemberResponse result = (MemberResponse) msg.obj;
				if (result == null) {
					Toast.makeText(SignInActivity.this, R.string.request_error,
							Toast.LENGTH_SHORT).show();
				} else {
					if (result.getSuccess()) {
						if (result.getRows() != null) {
							if (result.getRows().size() == 0) {
								Toast.makeText(SignInActivity.this,
										"未获取到相对应人员", Toast.LENGTH_SHORT).show();
							} else if (result.getRows().size() == 1) {
								memberList.add(0, result.getRows().get(0));
								mAdapter.notifyDataSetChanged();
								noDataLayout.setVisibility(View.GONE);
								memberListView.setVisibility(View.VISIBLE);
								signNum.setText(memberList.size() + "");
								Toast.makeText(SignInActivity.this, "签到成功",
										Toast.LENGTH_SHORT).show();
							} else if (result.getRows().size() > 0) {
//								showPopupWindow();
							}
						} else {
							Toast.makeText(SignInActivity.this, "未获取到相对应人员",
									Toast.LENGTH_SHORT).show();
						}
					} else {
						if (TextUtils.isEmpty(result.getMessage())) {
							Toast.makeText(SignInActivity.this, "签到失败",
									Toast.LENGTH_SHORT).show();
						} else {
							Toast.makeText(SignInActivity.this,
									result.getMessage(), Toast.LENGTH_SHORT)
									.show();
						}
					}
				}
				break;
			case FINGERPRINT_CODE:
				if (asyncFingerprint != null) {
					asyncFingerprint.setStop(false);
					asyncFingerprint.register();
				}
				break;
			case DELETE_SIGN_IN_CODE:
				for(MemberBean m : memberList){
					if(m.getId().equals(deleteSignId)){
						memberList.remove(m);
					}
				}
				mAdapter.notifyDataSetChanged();
				if (memberList.size() == 0) {
					showNoDataTip();
				}
				signNum.setText(memberList.size() + "");
				BaseResponse response = (BaseResponse) msg.obj;
                if(response != null){
                    Toast.makeText(SignInActivity.this,
                            response.getMessage(), Toast.LENGTH_SHORT)
                            .show();
                }
				break;
			}
		};
	};

	private void signIn(byte[] file) {
		Map<String, Object> uploadFileparams = new HashMap<String, Object>();
		HttpUploadThread httpUploadThread = new HttpUploadThread(
				Config.SIGN_URL + id, new HttpListener() {
					@Override
					public void onRequestFinish(BaseResponse response) {
						Message msg = mHandler.obtainMessage();
						msg.obj = response;
						msg.what = SIGN_IN_CODE;
						mHandler.sendMessage(msg);
					}

					@Override
					public void onNotLogin(BaseResponse response) {
						loginExpire();
						SignInActivity.this.onNotLogin(response);
					}
				}, file, uploadFileparams, MemberResponse.class);
		MyApplication.getInstance().getRequestQueue().execute(httpUploadThread);
	}

	@Override
	protected void onResume() {
		super.onResume();
        if (asyncFingerprint != null) {
            asyncFingerprint.setStop(false);
            asyncFingerprint.register();
        }
		mHandler.sendEmptyMessage(FINGERPRINT_CODE);
	}

    @Override
    protected void onPause() {
        super.onPause();
        if (asyncFingerprint != null) {
            asyncFingerprint.setStop(true);
        }
        mHandler.removeMessages(FINGERPRINT_CODE);
    }

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (SerialPortManager.getInstance().isOpen()) {
			SerialPortManager.getInstance().closeSerialPort();
		}
		unRegister();
	}

	private void showNoDataTip() {
		noDataTip.setVisibility(View.VISIBLE);
		connectionFailedTip.setVisibility(View.GONE);
		noDataLayout.setVisibility(View.VISIBLE);
		memberListView.setVisibility(View.GONE);
	}

	private void showconnectionFailedTip() {
		noDataTip.setVisibility(View.GONE);
		connectionFailedTip.setVisibility(View.VISIBLE);
		noDataLayout.setVisibility(View.VISIBLE);
		memberListView.setVisibility(View.GONE);
	}

	private void loginExpire() {
		dismissLoading();
		noDataTip.setVisibility(View.GONE);
		connectionFailedTip.setVisibility(View.GONE);
		noDataLayout.setVisibility(View.VISIBLE);
		memberListView.setVisibility(View.GONE);
	}

	private void updateData(Object data) {
		// memberList.clear();
		if (data == null) {
			Toast.makeText(SignInActivity.this, R.string.request_error,
					Toast.LENGTH_SHORT).show();
			showconnectionFailedTip();
		} else {
			MemberListResponse memeberListResponse = (MemberListResponse) data;
			if (memeberListResponse.getRows() != null) {
				if (memberListView == null) {
					return;
				}
				if (memeberListResponse.getRows().size() == 0) {
					showNoDataTip();
				} else {
                    memberList.clear();
					memberList.addAll(memeberListResponse.getRows());
					signNum.setText(memberList.size() + "");
					noDataLayout.setVisibility(View.GONE);
					memberListView.setVisibility(View.VISIBLE);
				}
			} else {
				showNoDataTip();
			}
		}
		mAdapter.notifyDataSetChanged();
		memberListView.setSelection(0);
		dismissLoading();
	}

	private void updateLoadData(Object data) {
		if (data == null) {
			Toast.makeText(SignInActivity.this, R.string.request_error,
					Toast.LENGTH_SHORT).show();
		} else {
			MemberListResponse memberListResponse = (MemberListResponse) data;
			if (memberListResponse.getRows() != null) {
				if (memberListResponse.getRows().size() == 0) {
					memberListView.setNoDataLoad();
				} else {
					if (memberListResponse.getRows().size() == pagesize) {
						memberListView.setPullLoadEnable(true);
					}
					memberList.addAll(memberListResponse.getRows());
					mAdapter.notifyDataSetChanged();
					noDataLayout.setVisibility(View.GONE);
					memberListView.setVisibility(View.VISIBLE);
				}
			} else {
				memberListView.setNoDataLoad();
			}
		}
		memberListView.stopLoadMore();
	}

	private void updateRefreshData(Object data) {
		if (data == null) {
			Toast.makeText(SignInActivity.this, R.string.request_error,
					Toast.LENGTH_SHORT).show();
		} else {
			MemberListResponse memberListResponse = (MemberListResponse) data;
			if (memberListResponse.getRows() != null) {
				if (memberListResponse.getRows().size() != 0) {
					CopyOnWriteArrayList<MemberBean> temp = new CopyOnWriteArrayList<MemberBean>();
					temp.addAll(memberListResponse.getRows());
					temp.addAll(memberList);
					memberList.clear();
					memberList = null;
					memberList = temp;
					mAdapter.notifyDataSetChanged();
				}
			}
		}
		memberListView.stopRefresh();
	}

	@Override
	public void onRequestFinish(BaseResponse response) {
		Message msg = mHandler.obtainMessage();
		msg.obj = response;
		msg.what = INFO_REQUEST_CODE;
		mHandler.sendMessage(msg);
	};

	@Override
	public void onNotLogin(BaseResponse response) {
		loginExpire();
		super.onNotLogin(response);
	}

	@Override
	public void onRefresh() {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("rows", "" + pagesize);
		params.put("code", "1");
		HttpThread httpThread = new HttpThread(Config.LOGIN_URL,
				new HttpListener() {
					@Override
					public void onRequestFinish(BaseResponse response) {
						Message msg = mHandler.obtainMessage();
						msg.obj = response;
						msg.what = REFRESH_INFO_REQUEST_CODE;
						mHandler.sendMessage(msg);
					}

					@Override
					public void onNotLogin(BaseResponse response) {
						loginExpire();
						SignInActivity.this.onNotLogin(response);
					}
				}, params, CampaignListResponse.class);
		MyApplication.getInstance().getRequestQueue().execute(httpThread);
	}

	@Override
	public void onLoadMore() {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("rows", "" + pagesize);
		params.put("code", "0");
		HttpThread httpThread = new HttpThread(Config.LOGIN_URL,
				new HttpListener() {
					@Override
					public void onRequestFinish(BaseResponse response) {
						Message msg = mHandler.obtainMessage();
						msg.obj = response;
						msg.what = LOAD_INFO_REQUEST_CODE;
						mHandler.sendMessage(msg);
					}

					@Override
					public void onNotLogin(BaseResponse response) {
						loginExpire();
						SignInActivity.this.onNotLogin(response);
					}
				}, params, CampaignListResponse.class);
		MyApplication.getInstance().getRequestQueue().execute(httpThread);
	}

	public void notIdentification(View view) {
        DialogFragmentTip dialog = new DialogFragmentTip();
		Bundle bundle = new Bundle();
		bundle.putString("id", id);
		dialog.setArguments(bundle);
        dialog.show(getFragmentManager(), "tip_dialog");
	}

    public class SignBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            initData();
        }
    }
}
